# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

from pylons import url
from pylons.i18n import lazy_ugettext as _

from sqlalchemy import select, func, or_

from webhelpers.html.tags import link_to, literal

from chowa.model.organization import District, Division
from hrms.model.person import Employee
from hrms.model.organization import Order
from hrms.lib.base import Session

class Error(object): pass


class DivisionSizeError(Error):
    def __init__(self, district_id):
        self.district_id = district_id
    
    def message(self, division):
        link = link_to(division.name, url(controller='org/employees',
                                          action='index',
                                          relation='division',
                                          id=division.id))
        return literal(_('Too few employees in %s') % link)
        
    def seek(self):
        query = Session.query(Division)
        divisions = query.filter_by(district_id=self.district_id,
                                    is_disabled=False)
        errors = [self.message(division)
                  for division in divisions if len(division.employees) < division.type.min_size]
        return errors


class NoOfficeError(Error):
    def __init__(self, district_id):
        self.district_id = district_id
    
    def message(self, employee):
        link = link_to(unicode(employee), url(controller='profile',
                                              action='index',
                                              id=employee.id))
        return literal(_('Employee %s has no office') % link)
    
    def seek(self):
        query = Session.query(Employee).join(Division)
        employees = query.filter(Employee.office_id == None) \
                         .filter(Employee.is_employee == True) \
                         .filter(Division.district_id == self.district_id)
        errors = [self.message(employee) for employee in employees]
        return errors
    

error_types = [
    DivisionSizeError,
    NoOfficeError,
]

def get_errors(district_id):
    errors = []
    for _type in error_types:
        error = _type(district_id)
        errors += error.seek()
    return errors
